// src/web/static/js/video_table.js 修改部分
const { createApp } = Vue;

createApp({
  data() {
    return {
      videos: [],
      searchQuery: '',
      loading: true,
      error: null,
      currentPage: 1,
      itemsPerPage: 10
    };
  },
  methods: {
    performSearch() {
      const trimmed = this.searchQuery.trim();
      this.searchQuery = trimmed;
      this.currentPage = 1;
    },
    // ✅ 新增方法：跳转到添加页面
    goToAddPage() {
      window.location.href = '/video_add';
    }
  },
  computed: {
    filteredVideos() {
      if (!this.searchQuery.trim()) return this.videos;

      const query = this.searchQuery.toLowerCase().trim();

      return this.videos.map(video => {
        const highlight = (text, keyword) => {
          if (!text || !keyword) return text;
          const regex = new RegExp(`(${keyword})`, 'gi');
          return text.replace(regex, '<span class="highlight">$1</span>');
        };

        return {
          ...video,
          video_title: highlight(video.video_title, this.searchQuery),
          platform: highlight(video.platform, this.searchQuery),
          brand: video.brand ? highlight(video.brand, this.searchQuery) : '-'
        };
      });
    },
    paginatedVideos() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredVideos.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.filteredVideos.length / this.itemsPerPage);
    }
  },
  mounted() {
    fetch('/api/videos')
      .then(res => {
        if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
        return res.json();
      })
      .then(data => {
        this.videos = data;
        this.loading = false;
      })
      .catch(err => {
        console.error("❌ 请求失败:", err);
        this.error = '❌ 加载失败，请检查网络或后端是否运行';
        this.loading = false;
      });
  }
}).mount('#app');